<%@ page language="java" pageEncoding="UTF-8" %>
<!DOCTYPE html>

<html>
<head>
    <title>java后端websocket的简单实现</title>
</head>
<body>
<h2>Welcome</h2>
<input id="text" type="text">
<button onclick="sendMessage()">发送消息</button>
<hr>
<button onclick="closeWebSocket()">关闭连接</button>
<hr>
<div id="message"></div>

</body>
<script type="text/javascript">
    var websocket = null;
    if ('WebSocket' in window) {
        //连接webSocket，webSocket是一个协议--类似http
        websocket = new WebSocket("ws://localhost:8086/simpleWebSocket")
    } else {
        alert("当前浏览器不支持webSocket")
    }

    //连接发生错误
    websocket.onerror = function () {
        setMessaggeInnerHTML("连接发生错误");
    }
    //打开回调方法
    websocket.onopen = function () {
        setMessaggeInnerHTML("WebSocket 连接成功");
    }
    //接受回调方法
    websocket.onmessage = function (event) {
        setMessaggeInnerHTML(event.data);
    }

    //关闭回调方法
    websocket.onclose = function (event) {
        setMessaggeInnerHTML(event.data);
    }


    function setMessaggeInnerHTML(innerHTML) {
        document.getElementById("message").innerHTML += innerHTML + '<br/>';
    }

    //发消息
    function sendMessage() {
        var message = document.getElementById("text").value;
        websocket.send(message);
    }

    //关闭连接
    function closeWebSocket() {
        websocket.close();
    }


</script>

</html>
